import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import message from '@/components/common/message'
import {
  createOrUpdateClass,
  getClassById,
  getClassStudents,
} from '@/request/class'

export interface Teacher {
  name: string
  phone: string
  tid?: string
  gender: string
}

export interface Student {
  name: string
  phone: string
  sid: string
  gender: string
}

export function useClassManagement() {
  const router = useRouter()
  const route = useRoute()

  // 判断是否为编辑模式
  const isEditMode = computed(() => !!route.params.cid)

  // 表单数据
  const schoolName = ref('小花狮实验学校')
  const schoolStage = ref('高中（3年制）')
  const grade = ref<number>(1)
  const studentCount = ref('')
  const className = ref('')
  const classId = ref('')

  // 附加服务选择
  const enableMiniProgram = ref(true)
  const enableAssistant = ref(true)

  // 教师和学生数据
  const teachers = ref<Teacher[]>([])
  const students = ref<Student[]>([])

  // 年级选项
  const gradeOptions = [
    { value: 1, label: '一年级' },
    { value: 2, label: '二年级' },
    { value: 3, label: '三年级' },
    { value: 4, label: '四年级' },
    { value: 5, label: '五年级' },
    { value: 6, label: '六年级' },
  ]

  // 加载班级数据
  async function loadClassData() {
    if (!route.params.cid)
      return

    try {
      const cid = route.params.cid as string
      const response = await getClassById({ cid })
      const classData = response.entry

      // 填充表单数据
      schoolName.value = classData.school
      if (classData.stageType === 3) {
        schoolStage.value = '高中（3年制）'
      }
      grade.value = classData.gradeInt
      studentCount.value = String(classData.studentsNum)
      className.value = classData.name
      classId.value = classData.cid

      // 加载教师列表
      teachers.value = classData.teachers.map(t => ({
        name: t.name || '',
        phone: t.data || '',
        tid: t.tid || '',
        gender: t.gender || '',
      }))

      // 加载学生列表
      await loadStudents()
    }
    catch (error) {
      console.error('获取班级数据失败:', error)
      message.error('获取班级数据失败')
    }
  }

  // 加载学生列表
  async function loadStudents() {
    if (!classId.value)
      return

    try {
      const response = await getClassStudents({ cid: classId.value })
      students.value = response.entries.map(entry => ({
        name: entry.name || '',
        phone: entry.phone || '',
        sid: entry.sid || '',
        gender: entry.gender || '',
      }))
    }
    catch (error) {
      console.error('获取学生列表失败:', error)
    }
  }

  // 创建或更新班级
  async function handleCreateClass() {
    if (!grade.value || !studentCount.value || !className.value) {
      message.error('请填写完整的班级信息')
      return
    }

    try {
      const data: any = {
        gradeInt: grade.value,
        name: className.value,
        school: schoolName.value,
        stageType: 3,
      }

      if (isEditMode.value && classId.value) {
        data.cid = classId.value
      }

      const response = await createOrUpdateClass(data)

      // 如果是新建班级，保存班级ID用于后续操作
      if (!isEditMode.value && response.entry.classId) {
        classId.value = response.entry.classId
      }

      message.success(isEditMode.value ? '班级更新成功' : '班级创建成功')
      router.push('/class')
    }
    catch (error) {
      console.error(isEditMode.value ? '更新班级失败:' : '创建班级失败:', error)
      message.error(isEditMode.value ? '更新班级失败' : '创建班级失败')
    }
  }

  function getGradeName(gradeValue: number | null) {
    if (gradeValue === null)
      return ''
    const option = gradeOptions.find(opt => opt.value === gradeValue)
    return option ? option.label : ''
  }

  function handleBack() {
    router.back()
  }

  return {
    // 状态
    isEditMode,
    schoolName,
    schoolStage,
    grade,
    studentCount,
    className,
    classId,
    enableMiniProgram,
    enableAssistant,
    teachers,
    students,
    gradeOptions,

    // 方法
    loadClassData,
    loadStudents,
    handleCreateClass,
    getGradeName,
    handleBack,
  }
}
